import axios from 'axios'
import { message } from '@/utils/resetMessage'

import { getToken, clearLocalStorage, getLoginType } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 1000*60, // request timeout
  // headers: {
  //   'Cache-Control': 'no-cache'
  // }

})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (getToken()) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['SESSION'] = getLoginType() === 'admin' ? `${ getToken() } ` : ''
      
      config.headers['Content-Type']= 'application/json';
    }
    if (config.method == 'post') {
      config.data = {
        ...config.data,
        _t: Date.parse(new Date()) / 1000
      }
    } else if (config.method == 'get') {
      config.params = {
        _t: Date.parse(new Date()) / 1000,
        ...config.params
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '20000') {
      message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return res;
  },
  error => {
    
    message({
      message: `请求失败,${error.response.data.message}`,
      type: 'error',
      duration: 5 * 1000
    })
    if (error.response.status === 401){
      clearLocalStorage()
      setTimeout(()=>{
        location.reload()
      },300)
    }
    
    return Promise.reject(error)
  }
)

export default service
